package com.logansoft.zhxypkoa.components;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.rest.core.event.AbstractRepositoryEventListener;
import org.springframework.stereotype.Component;

import com.logansoft.zhxypkoa.domain.sys.User;
import com.logansoft.zhxypkoa.utils.RegexUtils;
import com.logansoft.zhxypkoa.utils.RestVerifyUtils;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class UserListener extends AbstractRepositoryEventListener<User> {

	@Override
	protected void onBeforeCreate(User entity) {
		// TODO Auto-generated method stub
		super.onBeforeCreate(entity);
		log.debug("username: " + entity.getUsername());
		if (StringUtils.isEmpty(entity.getUsername())) {
			RestVerifyUtils.rejectValue(entity, "username", "username.empty", "用户名不能为空");
		} else if (entity.getUsername().length() < 5 || entity.getUsername().length() > 20) {
			RestVerifyUtils.rejectValue(entity, "username", "username.length", "用户名长度为5-20位");
		}
		if (StringUtils.isEmpty(entity.getOrgPassword())) {
			RestVerifyUtils.rejectValue(entity, "orgPassword", "orgPassword.empty", "密码不能为空");
		} else if (entity.getOrgPassword().length() < 6 || entity.getOrgPassword().length() > 20) {
			RestVerifyUtils.rejectValue(entity, "orgPassword", "orgPassword.length", "密码长度为6-20位");
		}
		entity.setPassword(DigestUtils.md5Hex(entity.getOrgPassword()));
		if (entity.getSexe() > 2) {
			RestVerifyUtils.rejectValue(entity, "sexe", "sexe.error", "性别选择错误");
		}
		if (entity.getAge() < 0 || entity.getAge() > 150) {
			RestVerifyUtils.rejectValue(entity, "age", "age.error", "年龄大小范围为0~150岁");
		}
		if (StringUtils.isNotEmpty(entity.getPhone()) && RegexUtils.isMobileSimple(entity.getPhone())) {
			RestVerifyUtils.rejectValue(entity, "phone", "phone.error", "手机号码格式错误");
		}
		if (StringUtils.isNotEmpty(entity.getEmail()) && RegexUtils.isEmail(entity.getEmail())) {
			RestVerifyUtils.rejectValue(entity, "email", "email.error", "邮箱格式错误");
		}
	}

}
